import os
import sys
import numpy as np

def verify_result(real_result, golden):

    with open("./common.h", "r") as f:
        lines = f.readlines()
        # Parse typedef float DTYPE_SELF;
        for line in lines:
            if "typedef _Float32 DTYPE_SELF" in line:
                dtype = np.float32
                break
            elif "typedef _Float16 DTYPE_SELF" in line:
                dtype = np.float16
                break
            elif "typedef int32_t DTYPE_SELF" in line:
                dtype = np.int32
                break
            elif "typedef double DTYPE_SELF" in line:
                dtype = np.float64
                break

    real_result = np.fromfile(real_result, dtype=dtype) # 从bin文件读取实际运算结果
    golden = np.fromfile(golden, dtype=dtype) # 从bin文件读取预期运算结果
    
    if golden.dtype == np.float16:
        loss = 1e-3  # 容忍偏差，一般fp16要求绝对误差和相对误差均不超过千分之一 
    else:
        loss = 1e-4
    minimum = 10e-10
    result = np.abs(real_result - golden)  # 计算运算结果和预期结果偏差
    deno = np.maximum(np.abs(real_result), np.abs(golden))  # 获取最大值并组成新数组
    result_atol = np.less_equal(result, loss)  # 计算绝对误差
    result_rtol = np.less_equal(result / np.add(deno, minimum), loss)  # 计算相对误差
    if not result_rtol.all() and not result_atol.all():
        if np.sum(result_rtol == False) > real_result.size * loss and np.sum(result_atol == False) > real_result.size * loss:  # 误差超出预期时返回打印错误，返回对比失败
            print("[ERROR] result error")
            input_self = np.fromfile("./input/input_self.bin", dtype=dtype)
            input_index = np.fromfile("./input/input_index.bin", dtype=np.int32)
            input_src = np.fromfile("./input/input_src.bin", dtype=dtype)
            print(f"input_self: {input_self}")
            print(f"input_index: {input_index}")
            print(f"input_src: {input_src}")
            print(f"Expected {golden}, Shape {golden.shape}, Got {real_result}, Shape {real_result.shape}")
            print(f"Absolute error: {np.abs(golden - real_result)}")
            return False
    print("test pass")
    return True
    """
    if not np.allclose(real_result, golden, atol=loss, rtol=loss):
        with np.printoptions(threshold=np.inf):
            # Disable ommission
            print("[ERROR] result error")
            input_self = np.fromfile("./input/input_self.bin", dtype=dtype)
            input_index = np.fromfile("./input/input_index.bin", dtype=np.int32)
            input_src = np.fromfile("./input/input_src.bin", dtype=dtype)
            print(f"input_self: {input_self}")
            print(f"input_index: {input_index}")
            print(f"input_src: {input_src}")
            print(f"Expected {golden}, Shape {golden.shape}, Got {real_result}, Shape {real_result.shape}")
            print(f"Absolute error: {np.abs(golden - real_result)}")
        return False
    print("test pass")
    return True
    """

if __name__ == '__main__':
    verify_result(sys.argv[1],sys.argv[2])
